package com.sk.weichat.util;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;

import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MediaHelper {

    private ExecutorService executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Integer.MAX_VALUE,
            15L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());

    private Handler mHandler;

    private MediaHelper() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    public static MediaHelper getInstance() {
        return SingletonHolder.instance;
    }

    static class SingletonHolder {
        static MediaHelper instance = new MediaHelper();
    }

    // and _size < 1048576
    static String fileSelection = "(_data like '%.rar' and _size > 10240) or (_data like '%.zip' and _size > 10240) or (_data like '%.txt' and _size > 1024) or (_data like '%.rtf' and _size > 1024) or (_data like '%.apk' and _size > 10240) or (_data like '%.cad' and _size > 10240)";
    static String imageSelection = "(_data like '%.png' and _size > 10240) or (_data like '%.jpg' and _size > 10240)";
    static String videoSelection = "(_data like '%.mp4' and _size > 10240) or (_data like '%.avi' and _size > 10240)";
    static String audioSelection = "(_data like '%.mp3' and _size > 10240)or(_data like '%.amr' and _size > 10240)";
    static String officeSelection = "(_data like '%.doc') or (_data like '%.xls') or (_data like '%.ppt') or (_data like '%.pdf') or (_data like '%.docx') or (_data like '%.xlsx') or (_data like '%.pptx') or (_data like '%.cad')";

    //其他文件
    public void getMediaFiles(ContentResolver contentResolver, OnQueryListener listener) {
        executorService.submit(queryTask(MediaStore.Files.getContentUri("external"), fileSelection, contentResolver, listener));
    }

    public void getMediaImages(ContentResolver contentResolver, OnQueryListener listener) {
        executorService.submit(queryTask(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageSelection, contentResolver, listener));
    }


    public void getMediaAudio(ContentResolver contentResolver, OnQueryListener listener) {

        executorService.submit(queryTask(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioSelection, contentResolver, listener));
    }


    public void getMediaVideo(ContentResolver contentResolver, OnQueryListener listener) {

        executorService.submit(queryTask(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoSelection, contentResolver, listener));
    }

    //office文档
    public void getMediaOfficeDoc(ContentResolver contentResolver, OnQueryListener listener) {

        executorService.submit(queryTask(MediaStore.Files.getContentUri("external"), officeSelection, contentResolver, listener));
    }


    //查询回调接口
    public interface OnQueryListener {
        void onSuccess(List<File> files);

        void onFailed(String msg);
    }

    public @Nullable
    List<File> getFilesQueryCache() {
        return queryCache.get(fileSelection);
    }

    public @Nullable
    List<File> getAudioQueryCache() {
        return queryCache.get(audioSelection);
    }

    public @Nullable
    List<File> getVideoQueryCache() {
        return queryCache.get(videoSelection);
    }

    public @Nullable
    List<File> getImageQueryCache() {
        return queryCache.get(imageSelection);
    }

    public @Nullable
    List<File> getOfficeQueryCache() {
        return queryCache.get(officeSelection);
    }

    //内存缓存查询结果
    private Map<String, List<File>> queryCache = new HashMap<>();

    private Runnable queryTask(Uri uri, String selection, ContentResolver resolver, OnQueryListener listener) {
        WeakReference<OnQueryListener> reference = new WeakReference<>(listener);


        return new Runnable() {
            @Override
            public void run() {

                Log.e("MediaHelper", "queryTask running");
                try {
                    List<File> files = new ArrayList<>();
                    // 要查的列
                    String[] projection = {
                            MediaStore.MediaColumns.DATA
                    };
                    // 条件
                    // 排序
                    String sortOrder = MediaStore.MediaColumns.DATE_MODIFIED + " desc";
                    Cursor cursor = resolver.query(uri, projection, selection, null, sortOrder);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            String path = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
                            files.add(new File(path));
                        }
                        //缓存查询结果
                        queryCache.put(selection, files);
                        //回调
                        if (null != reference.get()) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    reference.get().onSuccess(files);
                                }
                            });
                        } else {
                            Log.e("MediaHelper", "OnQueryListener is null");
                        }
                        cursor.close();
                    }
                    Log.e("MediaHelper", "queryTask success");
                } catch (Exception e) {
                    Log.e("MediaHelper", "queryTask failed:" + e.getMessage());
                    if (reference.get() != null) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                reference.get().onFailed("查询失败");
                            }
                        });

                    }
                }
            }
        };
    }


}
